package org.paybiz.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.paybiz.constant.PayConstant;
import org.paybiz.core.PayCallbackHandler;
import org.paybiz.model.PayResultDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author nassir.wen
 * @date 2013-1-15上午10:33:41
 */
@Controller
@RequestMapping(value = "/pay")
public class PayCallbackController {
    
    private final static Log logger = LogFactory.getLog(PayCallbackController.class);
    
    @Autowired
    private PayCallbackHandler payCallbackHandler; 
    
    /**
     * 同步回调
     * @author nassir.wen
     * @date 2013-1-15上午10:38:33
     * @return
     */
    @RequestMapping(value = "synCallback", method = {RequestMethod.GET,RequestMethod.POST})
    public String synCallback(Model model,HttpServletRequest request,HttpServletResponse response){
        logger.info("同步回调");
        PayResultDO payResult = verifyPayCallbackResult(request, response);
        model.addAttribute("payResult", payResult);
        return "payResultParam";
    }
    
    /**
     * 异步回调
     * @author nassir.wen
     * @date 2013-1-15上午11:01:57
     * @param request
     * @param response
     */
    @RequestMapping(value = "asynCallback", method = {RequestMethod.GET,RequestMethod.POST})
    public void asynCallback(HttpServletRequest request,HttpServletResponse response){
        logger.info("异步回调");
        PayResultDO payResult = verifyPayCallbackResult(request, response);
        payCallbackHandler.sendAsynResult(request, response,payResult.getResult());
    }
    
    private PayResultDO verifyPayCallbackResult(HttpServletRequest request,HttpServletResponse response){
        PayResultDO payResult = payCallbackHandler.verifyPayCallbackResult(request, response);
        if(payResult.getResult() == PayConstant.RESULT_SUCCESS){
            logger.info(PayConstant.getPayTypeValue(payResult.getPayType()) + "回调通知支付成功");
        }
        return payResult;
    }
}
